package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.entity.Announcement;
import com.example.service.AnnouncementService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("announcements")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;


    /**
     * 公告分页查询
     * @return
     */
    @GetMapping("/getPageAnnouncement/{current}/{size}")
    public R getPageAnnouncement(@PathVariable int current,@PathVariable int size,Announcement announcement){


        IPage page =new Page(current,size);
        LambdaQueryWrapper<Announcement> lqw =new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(announcement.getTitle()),Announcement::getTitle,announcement.getTitle());

        IPage page1 = announcementService.page(page,lqw);

        return R.success("公告分页查询！",page1);
    }



    /**
     * 查询所有公告
     * @return
     */
    @GetMapping("/getAllAnnouncement")
    public R getAllAnnouncement(){

        List<Announcement> list = announcementService.list();
        return R.success("查询所有公告！",list);
    }

    /**
     * 添加公告
     * @return
     */
    @PostMapping("/addAnnouncement")
    public R addAnnouncement(@RequestBody Announcement announcement){

        LambdaQueryWrapper<Announcement> lqw =new LambdaQueryWrapper<>();
        lqw.eq(Strings.isNotEmpty(announcement.getTitle()),Announcement::getTitle,announcement.getTitle());
        //1.查询数据库此公告是否存在
        Announcement one = announcementService.getOne(lqw);

        //2.不存在在添加
        if (one==null){
            boolean save = announcementService.save(announcement);
            if (save){
                return R.success("添加公告成功！",null);
            }else {
                return R.error("添加公告失败！");
            }
        }else {
            //3.存在
            return R.error("公告存在！添加失败！");
        }
    }

    /**
     * 通过id修改公告
     * @return
     */
    @PutMapping("/updateAnnouncement")
    public R updateAnnouncement(@RequestBody Announcement announcement){
        boolean b = announcementService.updateById(announcement);
        if (b){
           return R.success("通过id修改公告成功",announcement);
        }else {
           return R.error("通过id修改公告失败！");
        }
    }

    /**
     * 通过id删除公告
     * @return
     */
    @DeleteMapping("/deleteAnnouncement/{id}")
    public R deleteAnnouncement(@PathVariable int id){

        boolean b = announcementService.removeById(id);
        if (b){
           return R.success("通过id删除公告成功",id);
        }else {
           return R.error("通过id删除公告失败！");
        }
    }

}

